import { getGeoSource } from '@/api/api'
import * as Cesium from "cesium";

import { GeoJsonDataSource, Color, Cartesian3, PinBuilder } from 'cesium';

export const initGeo = async (layer, viewer) => {
    let params = {
        service: 'wfs',
        version: '1.0.0',
        request: 'Getfeature',
        typeName: layer, // 图层名称
        maxFeat: 50,
        outputFormat: 'application/json'
    }

    let res = await getGeoSource(params)

    let dataSource = await GeoJsonDataSource.load(res)
    viewer.dataSources.add(dataSource);

    if (layer === 'xm_shoppoint') {
        dataSource.clustering.enabled = true;
        dataSource.clustering.pixelRange = 50;
        dataSource.clustering.minimumClusterSize = 2;
        setClusterStyle(dataSource)
    };

    let entities = dataSource.entities.values;
    getType(layer, entities)
}

const getType = (layer, entities) => {
    switch (layer) {
        case 'xm_shoppoint':
            entities.forEach(v => {
                // v.position._value.z += 50.0
                // v.point = {
                //     color: Cesium.Color.RED,    //点位颜色
                //     pixelSize: 20              //像素点大小
                // }
                v.billboard = undefined
                v.label = {
                    text: v._name,
                    scale: 0.6,
                    // pixelOffset: new Cesium.Cartesian2(0.0, -20.0),
                    backgroundColor: Color.CORNFLOWERBLUE,
                    showBackground: true,
                    eyeOffset: new Cartesian3(0, 0, -1000)
                }
            })
            break;
        case 'xm_lrdl':
            entities.forEach(v => {
                v.polyline.material.color = Color.GAINSBORO
            })
            break;
        case 'xm_building':
            entities.forEach(v => {
                v.polygon.outline = false
                let floor = v.properties.floor._value
                if (floor < 5) {
                    v.polygon.material = Color.LIGHTGOLDENRODYELLOW.withAlpha(0.5)
                } else if (floor >= 5 && floor < 10) {
                    v.polygon.material = Color.MOCCASIN.withAlpha(0.5)
                } else if (floor >= 10 && floor < 15) {
                    v.polygon.material = Color.GOLD.withAlpha(0.5)
                } else {
                    v.polygon.material = Color.ORANGE.withAlpha(0.5)
                }
                v.polygon.extrudedHeight = floor * 10;
            })
            break;
    }
}

const setClusterStyle = (dataSource) => {

    const pinBuilder = new PinBuilder()

    dataSource.clustering.clusterEvent.addEventListener(
        function (clusteredEntities, cluster) {

            cluster.label.show = false
            cluster.billboard.show = true
            cluster.billboard.eyeOffset = new Cartesian3(0, 0, -1000)

            cluster.billboard.image = pinBuilder.fromText(clusteredEntities.length, Color.TOMATO, 58).toDataURL()
        }
    )
}